package com.xiangban.yanglaodajie_platform.service;


import com.xiangban.yanglaodajie_platform.dao.*;
import com.xiangban.yanglaodajie_platform.entity.*;
import com.xiangban.yanglaodajie_platform.entity.dto.OrderNoDto;
import com.xiangban.yanglaodajie_platform.entity.dto.ShoppingCartDto;
import com.xiangban.yanglaodajie_platform.entity.dto.UserDto;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResult;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiangban.yanglaodajie_platform.utils.CommonUtils.BizEmpty;


/**
 * @Author Mr. MaYaYun
 * @Data 2021/3/17 16:16
 */

@Service
public class ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AccumulatePointsMapper accumulatePointsMapper;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private WalletLogMapper walletLogMapper;
    @Autowired
    private ShopLoginMapper shopLoginMapper;

    public Object getPage(ShoppingCart shoppingCart) {
        shoppingCart.setUserId(Integer.parseInt(commonUtils.getUserId(request)));

        List<ShoppingCartDto> shop = shoppingCartMapper.getShopName(shoppingCart);//根据用户id查询商家名字和id
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (ShoppingCartDto cart : shop) {

            HashMap<String, Object> map1 = new LinkedHashMap<>();
            //获取商家id和用户id 获取商品列表
            ShoppingCart shoppingCart1 = new ShoppingCart();
            shoppingCart1.setShopId(cart.getShopId());
            shoppingCart1.setUserId(shoppingCart.getUserId());
            List<ShoppingCartDto> productList = shoppingCartMapper.getProductList(shoppingCart1);//根据用户id和商家id查询
            if (productList.size() >0){
                map1.put("shopName",cart.getShopName());
                map1.put("shopId",cart.getShopId());
                map1.put("shopLogo",cart.getShopLogo());
                map1.put("isDispatching",cart.getIsDispatching());
                map1.put("flag",false);


                map1.put("data",productList);
                maps.add(map1);
            }
        }
        return maps;
    }

    public void saveAndUpdate(ShoppingCart shoppingCart){//参数：商品id
        shoppingCart.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        Goods info = goodsMapper.findInfo(shoppingCart.getGoodsId());//查出商品详情age

        UserDto userDto = new UserDto();
        userDto.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        UserDto userInfoById = userMapper.getUserInfoById(userDto);
        String cardNo = userInfoById.getCardNo();
        if (info.getAge() != null){
            if (cardNo.length() != 18 ){//身份证号不等于18位年龄不符合
                throw new BizException(ApiResultCode.AGE_ERROR);
            }
            String idCard = cardNo.substring(6, 10);//截取身份证号
            int age = Integer.parseInt(idCard);
            int yyyy = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
            int i = yyyy - age;//当前用户年龄
            if (i < info.getAge()){
                throw new BizException(ApiResultCode.AGE_ERROR);
            }
        }
//        if (i >= info.getAge()){
//            //根据用户id和商品id  == null
//            ShoppingCart shoppingCart1 = shoppingCartMapper.getShoppingCart(shoppingCart);
//            if (shoppingCart1 == null){
//                ShoppingCart shopIdAndClassifyId = shoppingCartMapper.findShopIdAndClassifyId(shoppingCart);
//                shoppingCart.setClassifyId(shopIdAndClassifyId.getClassifyId());
//                shoppingCart.setShopId(shopIdAndClassifyId.getShopId());
//                shoppingCart.setNumber(1);
//                shoppingCart.setGoodsLogo(shopIdAndClassifyId.getGoodsLogo());
//                shoppingCartMapper.saveShoppingCart(shoppingCart);
//                return 1;
//            }else {
//                Integer  sum = 0;
//                Integer number = shoppingCart1.getNumber();
//                if (shoppingCart.getStatus()==1){
//                    sum = number+1;
//                    shoppingCart.setNumber(sum);
//                    shoppingCartMapper.updateShoppingCart(shoppingCart);
//                    return 1;
//                }else if (shoppingCart.getStatus()== -1 && number != 0){
//                    sum = number-1;
//                    shoppingCart.setNumber(sum);
//                    shoppingCartMapper.updateShoppingCart(shoppingCart);
//                    return 1;
//                }
//                return -1;
//            }
//        }else {
//            return -2;
//        }
            ShoppingCart shoppingCart1 = shoppingCartMapper.getShoppingCart(shoppingCart);
            if (shoppingCart1 == null){
                ShoppingCart shopIdAndClassifyId = shoppingCartMapper.findShopIdAndClassifyId(shoppingCart);
                shoppingCart.setClassifyId(shopIdAndClassifyId.getClassifyId());
                shoppingCart.setShopId(shopIdAndClassifyId.getShopId());
                shoppingCart.setNumber(1);
                shoppingCart.setGoodsLogo(shopIdAndClassifyId.getGoodsLogo());
                shoppingCartMapper.saveShoppingCart(shoppingCart);
            }else {
                Integer  sum = 0;
                Integer number = shoppingCart1.getNumber();
                if (shoppingCart.getStatus()==1){
                    sum = number+1;
                    shoppingCart.setNumber(sum);
                    shoppingCartMapper.updateShoppingCart(shoppingCart);
                    return ;
                }else if (shoppingCart.getStatus()== -1 && number != 0){
                    sum = number-1;
                    shoppingCart.setNumber(sum);
                    shoppingCartMapper.updateShoppingCart(shoppingCart);
                    return;
                }
                throw new BizException(ApiResultCode.NUMBER_NULL);
            }
    }
    /**
     * 订单结算
     * @param orderNoDto
     * @return
     */
    @Transactional
    public int Settlement(OrderNoDto orderNoDto){
        int userId = Integer.parseInt(commonUtils.getUserId(request));

        //判断订单状态是否能结算
        List<OrderNoDto> status = ordersMapper.findStatus(orderNoDto);
        if (status.size()>1){
            return -1;
        }
        //比较余额和订单价格
        Orders orderPriceSUM = ordersMapper.findOrderPriceSUM(orderNoDto);
        ShoppingCartDto accumulatePoints = ordersMapper.findAccumulatePoints(orderNoDto);
        BigDecimal bigDecimal = new BigDecimal(orderPriceSUM.getGoodsPrice());//订单价格
        BigDecimal newpoints = accumulatePoints.getNewpoints();//账户积分
        if (newpoints.compareTo(bigDecimal) == -1){//账户积分小于订单价格
            return -2;
        }
        List<Orders> ordersByOrdersNumber = accumulatePointsMapper.findOrdersByOrdersNumber(orderNoDto);//根据订单编号查订单
        HashMap<String, Object> map = new HashMap<>();
        map.put("newPoints",newpoints.subtract(bigDecimal));
        map.put("userId",userId);
            for (Orders ap : ordersByOrdersNumber) {
                //用户积分流水日志
                AccumulatePoints accumulatePoints1 = new AccumulatePoints();
                accumulatePoints1.setUserId(ap.getUserId());
                accumulatePoints1.setOrderNumber(ap.getOrderNumber());
                accumulatePoints1.setAccumulatePoints(new BigDecimal(ap.getGoodsPrice()));
                accumulatePoints1.setType(2);//流水类型(1:收入，2:支出)
                accumulatePoints1.setPayState(0);
                accumulatePoints1.setDescribe("商品消费");
                accumulatePoints1.setRecodeType(2);//记录类型 0 充值 1 打卡 2 商品消费 3 活动消费
                accumulatePointsMapper.saveAP(accumulatePoints1);
                //商家钱包日志  TODO
                WalletLog walletLog = new WalletLog();
                walletLog.setType(1);//1:收入、2:支出
                walletLog.setOrderNumber(ap.getOrderNumber());
                walletLog.setDescribe("商品收入");
                walletLog.setRecodeType(1);//记录类型 1：商品收入 2：退款
                walletLog.setShopId(ap.getShopId());
                walletLog.setMoney(new BigDecimal(ap.getGoodsPrice()));
                walletLogMapper.insertWalletLog(walletLog);
                //下单后商家加积分  TODO
                ShopLogin shopLogin = new ShopLogin();
                shopLogin.setWallet(bigDecimal);
                shopLogin.setShopId(ap.getShopId());
                shopLoginMapper.updateWallet(shopLogin);
            }

        //根据订单编号修改订单状态
                ordersMapper.updateOrderStatus(orderNoDto);
                return userMapper.updAccumulatePoints(map);
    }

    /**
     * 清空购物车
     * @param shoppingCart
     */
    public void clearAll(ShoppingCart shoppingCart) {//商家id 用户id
        if (BizEmpty(shoppingCart.getShopId())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (commonUtils.getUserId(request)!= null){
            shoppingCart.setUserId(Integer.parseInt(commonUtils.getUserId(request)));
        }
        shoppingCartMapper.delShoppingCartByShopId(shoppingCart);//根据user_id、shop_id 删除购物车
    }
}
